/**
 * Created by no1 on 2015/11/3.
 */
'use strict';
let DD = require('./daoLoader');
let F = require('../function')
let Base = require('./Base');
let util = require("util");
let sellRoleDao = new DD.mongoDB.SellRoleDao;
let authorityDao = new DD.redisDB.AuthorityDao;

let gitPermissByArr = function* (arr) {
  let retPermissTree = yield F.getDataFromDispatcher('sellPermissionDispatcher', 'findTreeByDis', {
    code: {$in: arr},
    status: 1
  });
  return retPermissTree.data
}
let gitPerlength = function*(data) {
  let len = data.length;
  for (let one of data) {
    one.nextPer = one.nextPer || [];
    len += one.nextPer.length;
  }
  return len;
}

/**
 * todo 获取带完整权限树的角色详情
 * @param rid
 */
let gitRoleTakepermissTree = function*(rid) {

  let retRedis = yield authorityDao.find('role:' + rid);

  if (!retRedis.data) {

    //获取角色数据
    let oneRole = yield gitRole(rid);
    if (oneRole.error == 1 || oneRole.data.length == 0) return F.returnData(1, oneRole.msg);
    oneRole = oneRole.data;
    //查询商家
    let retVendor = yield F.getDataFromDispatcher('vendorDispatcher', 'findByDis', {id: oneRole.vid, status: 1});
    if (retVendor.error == 1 || retVendor.data.length == 0) return F.returnData(1, '没有该商家');
    oneRole.vendorType = retVendor.data[0].type || 2;

    //根据角色权限组装树状数据
    let codes = oneRole.permissionCodes;
    let retPermissTree = yield F.getDataFromDispatcher('sellPermissionDispatcher', 'AllTreeByDis', {
      codes: codes,
      type: oneRole.vendorType
    });
    oneRole.permissionTree = retPermissTree.data;

    //存入redis 数据库
    yield authorityDao.save('role:' + rid, JSON.stringify(oneRole));

    retRedis = yield authorityDao.find('role:' + rid);
  }
  return F.returnData(0, 'ok', JSON.parse(retRedis.data));
}
let gitRole = function*(rid) {
  let arrDel = ['_id', '__v', '__t', 'createdAt', 'updateAt', 'status', 'permissionTree', 'primary']
    , opt = {};
  for (let one of arrDel) opt[one] = 0;
  let ret = yield sellRoleDao.getByQuery({rid: rid}, opt);
  if (ret.error == 1 || ret.data.length == 0) return F.returnData(1, '没有该角色');
  return F.returnData(0, ret.msg, ret.data[0]);
}

/**
 * 保存角色,主供接口addByinit使用
 * @param data
 * @returns {*}
 */
let saveRole = function* (data) {
  let parameters = {};
  parameters.name = data.name || '';
  parameters.vid = data.vid;
  parameters.status = 1;
  parameters.retain = data.retain;
  parameters.permissionCodes = [];

  //给角色添加所有权限
  if (data.name == "管理员") {
    let retper = yield F.getDataFromDispatcher('sellPermissionDispatcher', 'findByDis', {type: 2, status: 1});
    if (retper.error == 1) return F.returnData(1, retper.msg);
    for (let one of retper.data) parameters.permissionCodes.push(one.code);
  }

  //保存
  let ret = yield sellRoleDao.findAndSave({rid: 0}, parameters, 'rid');
  return ret;
};


function SellRoleDispatcher(data) {
  data = data || {};
  data.dao = data.dao || sellRoleDao;
  data.esDao = data.esDao || {};
  data.redisDao = data.redisDao || {};
  data.modelName = data.modelName || 'sellRole';
  data.modelType = data.modelType || 'mongo';
  this.data = data;
  Base.call(this, this.data);
};
util.inherits(SellRoleDispatcher, Base);
/**
 * todo 添加角色
 * @param fields
 * @returns {{error, msg, data}|{error, msg}}
 */
SellRoleDispatcher.prototype.add = function*(fields) {
  if (!fields.name) return F.returnData(1, '必须有名称');
  if (!fields.vid) return F.returnData(1, '必须商家id');
  let parameters = {};
  parameters.name = fields.name || '';
  parameters.vid = fields.vid;
  parameters.permissionCodes = fields.permissionCodes || [];
  parameters.status = 1;
  parameters.retain = 0;
  //验证商家是否存在
  let retVendor = yield F.getDataFromDispatcher('vendorDispatcher', 'findByDis', {id: parameters.vid});
  if (retVendor.error == 1 || retVendor.data.length != 1) return F.returnData(1, '没有该商家');
  //验证permissionCodes是否合法
  let permiss
  if (!!parameters.permissionCodes) {
    permiss = yield gitPermissByArr(parameters.permissionCodes);
    if (parameters.permissionCodes.length != (yield gitPerlength(permiss))) return F.returnData(1, 'permissionCodes对应结构有误');
  }
  //保存
  let ret = yield this.dao.findAndSave({rid: 0}, parameters, 'rid');
  if (ret.error == 1) return F.returnData(1, ret.msg, ret.data);
  let json = JSON.parse(JSON.stringify(ret.data));
  let retData = F.dataFilter(json, ['_id', 'permissionTree', 'createdAt', 'updateAt', '__v', 'status'], true)
  return F.returnData(0, ret.msg, retData);
};
/**
 * todo 获取商家角色列表
 * @param fields
 * @returns {{error, msg, data}|{error, msg}}
 */
SellRoleDispatcher.prototype.list = function*(fields) {
  if (!fields.vid) return F.returnData(1, '必须有商家id');
  let page = fields.page
    , pageSize = fields.pageSize
    , isPaging = fields.isPaging
    , status = fields.status || 1
    , ret = {}
    , Que = {}
    , count = {}
    , retData = {}
    , retDataList = []
    , arrDel = ['_id', '__v', '__t', 'createdAt', 'updateAt', 'permissionTree', 'primary', 'vid']
    , opt = {};
  for (let one of arrDel) opt[one] = 0;

  if (fields.act = 1) {
    //arrDel.permissionCodes = 0;
    //arrDel.retain = 0;
    //arrDel.status = 0;
    Que = {vid: fields.vid, status: status};
    //获取列表
    let ret = yield this.dao.getByQueryPor(Que, opt, {page: page, pageSize: pageSize}, {rid: -1});
    if (ret.error == 1 || ret.data.length == 0) return F.returnData(1, '没有这个商家', ret.data);
    //获取总数量
    count = yield this.dao.getCountByQuery(Que);
    if (count.error == 1) return F.returnData(1, count.msg, count.data);
    for (let one of ret.data) {
      let tmp = {};
      tmp.rid = one.rid;
      tmp.name = one.name;
      tmp.retain = one.retain;
      tmp.status = one.status;
      tmp.hasPermission = 0;
      if (one.permissionCodes.length > 0) tmp.hasPermission = 1;
      retDataList.push(tmp);
    }
  }


  if (isPaging == 1) {
    retData.list = retDataList;
    retData.count = count.data;
  } else retData = retDataList;
  return F.returnData(0, ret.msg, retData);
};
/**
 * todo 获取角色详情
 * @param fields
 * @returns {{error, msg, data}|{error, msg}}
 */
SellRoleDispatcher.prototype.detail = function*(fields) {
  if (!fields.rid) return F.returnData(1, '必须有rid');
  let oneRole
  if (fields.act == 1) oneRole = yield gitRoleTakepermissTree(fields.rid)
  if (fields.act == 2) oneRole = yield gitRole(fields.rid);
  if (fields.act == 3) {
    oneRole = yield gitRole(fields.rid);
    let tem = oneRole.data || {};
    oneRole.data = {name: tem.name, rid: tem.rid};
  }
  if (oneRole.error == 1) return F.returnData(1, oneRole.msg, oneRole.data);
  return F.returnData(0, oneRole.msg, oneRole.data);
};
/**
 * todo 更新
 * @param fields
 * @returns {{error, msg, data}|{error, msg}}
 */
SellRoleDispatcher.prototype.update = function* (fields) {
  if (!fields.rid) return F.returnData(1, '必须有rid');
  let rid = fields.rid;
  let parameters = {};
  if (!!fields.permissionCodes) parameters.permissionCodes = fields.permissionCodes;
  if (!!fields.name) parameters.name = fields.name;
  if (fields.status != null) parameters.status = fields.status;
  let ret = yield this.dao.findAndUpdate({rid: rid}, parameters);
  if (ret.error == 1) return F.returnData(1, ret.msg, ret.data);
  yield authorityDao.save('role:' + rid, '');
  return F.returnData(0, ret.msg, ret.data);
};
/**
 * 初始化商家中的角色
 * @param fields
 * @returns {{error, msg, data}|{error, msg}}
 */
SellRoleDispatcher.prototype.addByinit = function*(fields) {
  if (!fields.vid) return F.returnData(1, '必须商家id');

  //验证商家是否存在
  let retVendor = yield F.getDataFromDispatcher('vendorDispatcher', 'findByDis', {id: fields.vid});
  if (retVendor.error == 1 || retVendor.data.length != 1) return F.returnData(1, '没有该商家');

  let roleOfVid = yield  this.dao.getByQuery({vid: fields.vid});
  if (roleOfVid.error == 1 || roleOfVid.data.length > 0) return F.returnData(1, '该商家已经初始化,不了再执行');

  let roleArr = [
    {name: "管理员", retain: 1},
    {name: "店长", retain: 1},
    {name: "运营", retain: 0},
    {name: "客服", retain: 0}
  ];
  let retData = [];
  for (let role of roleArr) {
    let data = {};
    data.name = role.name;
    data.retain = role.retain;
    data.vid = fields.vid;

    //保存
    let ret = yield saveRole(data);
    //if (ret.error == 1) return F.returnData(1, ret.msg);
    //添加到返回数据中
    retData.push(ret.data);
  }

  //过滤数据
  let json = JSON.parse(JSON.stringify(retData));
  retData = F.dataFilter(json, ['_id', 'permissionTree', 'createdAt', 'updateAt', '__v', 'status'], true);
  return F.returnData(0, 'ok', retData);
};
/**
 * 内部调用
 * @param Que
 * @returns {{error, msg, data}|{error, msg}}
 */
SellRoleDispatcher.prototype.findByDis = function*(Que) {
  let arrDel = ['_id', '__v', '__t', 'createdAt', 'updateAt', 'status', 'permissionTree']
    , opt = {};
  for (let one of arrDel) opt[one] = 0;
  let ret = yield this.dao.getByQuery(Que, opt);
  if (ret.error == 1) F.returnData(1, ret.msg, ret.data);
  return F.returnData(0, ret.msg, ret.data);
};
/**
 * 内部调用
 * @param rid
 * @returns {*}
 */
SellRoleDispatcher.prototype.findTreeByDis = function*(rid) {
  return yield gitRoleTakepermissTree(rid);
};
module.exports = SellRoleDispatcher;